package com.sam.mvp.model;

import android.app.Application;

import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.ActivityScope;

import javax.inject.Inject;

import com.sam.api.cache.CommCache;
import com.sam.api.service.UserService;
import com.sam.mvp.entity.User;
import com.sam.mvp.contract.MainContract;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictDynamicKey;
import io.rx_cache2.Reply;
import okhttp3.ResponseBody;


@ActivityScope
public class MainModel extends BaseModel implements MainContract.Model {

    private int USERS_PRE_PAGE = 20;

    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public MainModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

    @Override
    public Observable<List<User>> getUsers(int since, boolean isUpdate) {

        return Observable.just(mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .getUsers(since, USERS_PRE_PAGE))
                .flatMap(new Function<Observable<List<User>>, ObservableSource<List<User>>>() {
                    @Override
                    public ObservableSource<List<User>> apply(Observable<List<User>> listObservable) throws Exception {
                        return mRepositoryManager
                                .obtainCacheService(CommCache.class)
                                .getUsers(listObservable, new DynamicKey(since), new EvictDynamicKey(isUpdate))
                                .map(new Function<Reply<List<User>>, List<User>>() {
                                    @Override
                                    public List<User> apply(Reply<List<User>> listReply) throws Exception {
                                        return listReply.getData();
                                    }
                                });
                    }
                });

    }

    @Override
    public Observable<ResponseBody> downloadFile(String url) {
        return mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .downloadFile(url);


    }


}